//
//  TSPickerTextField.m
//  chart
//
//  Created by xu on 15/8/2.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSPickerTextField.h"

#define PIKCER_VIEW_HEIGHT 120.f

@implementation TSPickerTextField{
    UIToolbar *inputAccessoryView;
    NSArray *sourceArray;
}

@synthesize pickerView;

- (id)initWithFrame:(CGRect)frame WithSourceArray:(NSArray *)array
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        [self setFont:FONT(12.f)];
        
        sourceArray = array;
    }
    
    return self;
}

- (void)drawRect:(CGRect)rect
{
    pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, currentDeviceWidth, PIKCER_VIEW_HEIGHT)];
    self.inputView = pickerView;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    
    /* default selectd item */
    [self setText:[sourceArray objectAtIndex:0]];
}

#pragma mark - inputAccessoryView with toolbar
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)done:(id)sender {
    [super resignFirstResponder];
    
    [self resignFirstResponder];
}

- (UIView *)inputAccessoryView {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        return nil;
    } else {
        if (!inputAccessoryView) {
            inputAccessoryView = [[UIToolbar alloc] init];
            inputAccessoryView.barStyle = UIBarStyleBlackTranslucent;
            inputAccessoryView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            [inputAccessoryView sizeToFit];
            CGRect frame = inputAccessoryView.frame;
            frame.size.height = 30.0f;
            inputAccessoryView.frame = frame;
            
            UIBarButtonItem *doneBtn =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done:)];
            UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
            
            NSArray *array = [NSArray arrayWithObjects:flexibleSpaceLeft, doneBtn, nil];
            [inputAccessoryView setItems:array];
        }
        return inputAccessoryView;
    }
}

#pragma mark - UIPickerViewDataSource, UIPickerViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [sourceArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [sourceArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [self setText:[sourceArray objectAtIndex:row]];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 20.f;
}

@end
